package com.nc.delivery_project.client.departments;

import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.add_department.AddDepartmentPlace;
import com.nc.delivery_project.client.department_details.DepartmentDetailsPlace;
import com.nc.delivery_project.client.request.DepartmentRequest;
import com.nc.delivery_project.client.statistics.StatisticsPlace;
import com.nc.delivery_project.shared.proxy.CityProxy;
import com.nc.delivery_project.shared.proxy.DepartmentProxy;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


public class DepartmentsView extends Composite {
    interface DepartmentViewUiBinder extends UiBinder<VerticalPanel, DepartmentsView> {
    }

    private static DepartmentViewUiBinder uiBinder = GWT.create(DepartmentViewUiBinder.class);

    private ListDataProvider<DepartmentProxy> dataProvider;

    private List<DepartmentProxy> dataList;

    ColumnSortEvent.ListHandler<DepartmentProxy> sortHandler;
    
    private ClientFactory clientFactory;
    

    @UiField
    VerticalPanel panel;

    @UiField
    TextBox filterTxtBox;

    @UiField
    DataGrid<DepartmentProxy> departmentsDataGrid;

    @UiField
    SimplePager pager;

    @UiField
    Button addBtn;
    
 //   @UiField
 //   Button statisticBtn;

    private DepartmentsPresenter presenter;

    public DepartmentsView() {
        initWidget(uiBinder.createAndBindUi(this));
    }

    public void setPresenter(DepartmentsPresenter presenter) {
        this.presenter = presenter;
    }

    public void start() {
        panel.setCellWidth(departmentsDataGrid, "100%");
        panel.setCellWidth(pager, "100%");

        departmentsDataGrid.setWidth("100%");
        departmentsDataGrid.setHeight("400px");
        departmentsDataGrid.setEmptyTableWidget(new HTML("No Data to Display"));

        pager.setDisplay(departmentsDataGrid);

        dataProvider = new ListDataProvider<>();
        dataProvider.setList(new ArrayList<DepartmentProxy>());

        sortHandler = new ColumnSortEvent.ListHandler<>(dataProvider.getList());

        initTableColumns(departmentsDataGrid, sortHandler);

        departmentsDataGrid.addColumnSortHandler(sortHandler);

        dataProvider.addDataDisplay(departmentsDataGrid);

        filterTxtBox.addKeyUpHandler(new KeyUpHandler() {
            @Override
            public void onKeyUp(KeyUpEvent event) {
                filter(filterTxtBox.getText());
            }
        });

        addBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                presenter.goTo(new AddDepartmentPlace(""));
            }
        });
 /*       statisticBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
         //   	 presenter.goTo(new StatisticsPlace(""));
            }
        });
        */
    }

    private void filter(String filteredName) {
        List<DepartmentProxy> filteredDepts = new ArrayList<>();
        for (DepartmentProxy dept : dataList) {
            if (String.valueOf(dept.getCity().getCityTitle()).contains(filteredName)) {
                filteredDepts.add(dept);
            }else if (String.valueOf(dept.getDeptId()).contains(filteredName)) {
                filteredDepts.add(dept);
            }else if (String.valueOf(dept.getCity().getStatePr().getStateTitle()).contains(filteredName)) {
                filteredDepts.add(dept);
            }else if (String.valueOf(dept.getCity().getStatePr().getCountry().getCountryTitle()).contains(filteredName)) {
                filteredDepts.add(dept);
            }
        }

        bindData(filteredDepts);
    }

    public void initTableColumns(DataGrid<DepartmentProxy> dataGrid, ColumnSortEvent.ListHandler<DepartmentProxy> sortHandler) {
        Column<DepartmentProxy, String> idCol = createIdCol(sortHandler);
        Column<DepartmentProxy, String> addressCol = createAddressCol(sortHandler);
        Column<DepartmentProxy, String> postalCodeCol = createPostalCodeCol(sortHandler);
        Column<DepartmentProxy, String> cityCol = createCityCol(sortHandler);
        Column<DepartmentProxy, String> stateCol = createStateCol(sortHandler);
        Column<DepartmentProxy, String> countryCol = createCountryCol(sortHandler);
        Column<DepartmentProxy, String> acceptedOrdersCol = createAcceptedOrdersCol(sortHandler);
        Column<DepartmentProxy, String> grantedOrdersCol = createIssuedOrdersCol(sortHandler);
        
        Column<DepartmentProxy, String> deptDetailsBtnCol = createDetailsBtnCol();
        
        dataGrid.addColumn(idCol, "ID");        
        dataGrid.addColumn(countryCol, "Country");
        dataGrid.addColumn(stateCol, "State/Province");
        dataGrid.addColumn(cityCol, "City");
        dataGrid.addColumn(addressCol, "Address");
        dataGrid.addColumn(postalCodeCol, "Postal Code"); 
        dataGrid.addColumn(acceptedOrdersCol, "Accepted orders");
        dataGrid.addColumn(grantedOrdersCol, "Granted orders");
       
        dataGrid.addColumn(deptDetailsBtnCol, "Details");
    }
    
	private Column<DepartmentProxy, String> createIssuedOrdersCol(ListHandler<DepartmentProxy> sortHandler) {
		Column<DepartmentProxy, String> col = new Column<DepartmentProxy, String>(new TextCell()) {
			@Override
            public String getValue(DepartmentProxy object) {
				return String.valueOf(object.getDeptId()-200);//нужно реальное поле IssuedOrders
            }
        };

        col.setSortable(true);
        sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
            @Override
            public int compare(DepartmentProxy o1, DepartmentProxy o2) {
            	 if (o1.getDeptId() == o2.getDeptId()) {//нужно реальное поле IssuedOrders
                     return 0;
                 } else {
                     return o1.getDeptId() > o2.getDeptId() ? 1 : -1;//нужно реальное поле IssuedOrders
                 }
            }
        });
        return col;
	}

	private Column<DepartmentProxy, String> createAcceptedOrdersCol(ListHandler<DepartmentProxy> sortHandler) {
		Column<DepartmentProxy, String> col = new Column<DepartmentProxy, String>(new TextCell()) {
			@Override
            public String getValue(DepartmentProxy object) {
				return String.valueOf(object.getDeptId()-202);//нужно реальное поле AcceptedOrders
            }
        };

        col.setSortable(true);
        sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
            @Override
            public int compare(DepartmentProxy o1, DepartmentProxy o2) {
            	 if (o1.getDeptId() == o2.getDeptId()) {//нужно реальное поле AcceptedOrders
                     return 0;
                 } else {
                     return o1.getDeptId() > o2.getDeptId() ? 1 : -1;//нужно реальное поле AcceptedOrders
                 }
            }
        });
        return col;
	}

	private Column<DepartmentProxy, String> createCountryCol(ListHandler<DepartmentProxy> sortHandler) {
		Column<DepartmentProxy, String> col = new Column<DepartmentProxy, String>(new TextCell()) {
			@Override
            public String getValue(DepartmentProxy object) {
				if(object.getCity().getStatePr()!=null)
					return String.valueOf(object.getCity().getStatePr().getCountry().getCountryTitle());
				else
					return "доработать!!!";
            }
        };

        col.setSortable(true);
        sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
            @Override
            public int compare(DepartmentProxy o1, DepartmentProxy o2) {
            	return o1.getCity().getStatePr().getCountry().getCountryTitle()
            			.compareToIgnoreCase(o2.getCity().getStatePr().getCountry().getCountryTitle());
            }
        });
        return col;
	}

	private Column<DepartmentProxy, String> createStateCol(ListHandler<DepartmentProxy> sortHandler) {
		Column<DepartmentProxy, String> col = new Column<DepartmentProxy, String>(new TextCell()) {
           

			@Override
            public String getValue(DepartmentProxy object) {
		
				if(object.getCity().getStatePr()!=null)
					return String.valueOf(object.getCity().getStatePr().getStateTitle());
				else
					return "доработать!!!";
            }
        };

        col.setSortable(true);
        sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
            @Override
            public int compare(DepartmentProxy o1, DepartmentProxy o2) {
            	return o1.getCity().getStatePr().getStateTitle().compareToIgnoreCase(o2.getCity().getStatePr().getStateTitle());
            }
        });
        return col;
	}

	private Column<DepartmentProxy, String> createIdCol(ColumnSortEvent.ListHandler<DepartmentProxy> sortHandler){
        Column<DepartmentProxy, String> col = new Column<DepartmentProxy, String>(new TextCell()) {
            @Override
            public String getValue(DepartmentProxy object) {
                return String.valueOf(object.getDeptId());
            }
        };

        col.setSortable(true);
        sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
            @Override
            public int compare(DepartmentProxy o1, DepartmentProxy o2) {
                if (o1.getDeptId() == o2.getDeptId()) {
                    return 0;
                } else {
                    return o1.getDeptId() > o2.getDeptId() ? 1 : -1;
                }
            }
        });
        return col;
    }
   

    private Column<DepartmentProxy, String> createCityCol(ColumnSortEvent.ListHandler<DepartmentProxy> sortHandler) {
		Column<DepartmentProxy, String> col= new Column<DepartmentProxy, String>(new TextCell()) {
			
			@Override
			public String getValue(DepartmentProxy arg0) {
				return arg0.getCity().getCityTitle();
			}
		};

		col.setSortable(true);
		sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
			
			@Override
			public int compare(DepartmentProxy o1, DepartmentProxy o2) {
				return  o1.getCity().getCityTitle().compareToIgnoreCase(o2.getCity().getCityTitle());
			}
		});
		
		return col;
	}

	private Column<DepartmentProxy, String> createPostalCodeCol(ColumnSortEvent.ListHandler<DepartmentProxy> sortHandler) {
		Column<DepartmentProxy, String> col = new Column<DepartmentProxy, String>(new TextCell()) {
			
			@Override
			public String getValue(DepartmentProxy arg0) {
				return arg0.getPostalCode();
			}
		};

		col.setSortable(true);
		sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
			
			@Override
			public int compare(DepartmentProxy o1, DepartmentProxy o2) {
				return  o1.getPostalCode().compareToIgnoreCase(o2.getPostalCode());
			}
		});;
		return col;
	}

	private Column<DepartmentProxy, String> createAddressCol(ColumnSortEvent.ListHandler<DepartmentProxy> sortHandler) {
		Column<DepartmentProxy, String> col = new Column<DepartmentProxy, String>(new TextCell()) {
			
			@Override
			public String getValue(DepartmentProxy arg0) {
				return arg0.getAddress();
			}
		};

		col.setSortable(true);
		sortHandler.setComparator(col, new Comparator<DepartmentProxy>() {
			
			@Override
			public int compare(DepartmentProxy o1, DepartmentProxy o2) {
				return  o1.getAddress().compareToIgnoreCase(o2.getAddress());
			}
		});;
		return col;
	}



    private Column<DepartmentProxy, String> createDetailsBtnCol() {
        Column<DepartmentProxy, String> detailsBtnCol = new Column<DepartmentProxy, String>(new ButtonCell()) {
            @Override
            public String getValue(DepartmentProxy object) {
                return "->";
            }
        };
        detailsBtnCol.setFieldUpdater(new FieldUpdater<DepartmentProxy, String>() {
            @Override
            public void update(int index, DepartmentProxy object, String value) {
                presenter.goTo(new DepartmentDetailsPlace(String.valueOf(dataProvider.getList().get(index).getDeptId())));
            }
        });
        return detailsBtnCol;
    }

    public void setDataList(List<DepartmentProxy> dataList) {
        this.dataList = dataList;
        bindData(dataList);
    }

    public void bindData(List<DepartmentProxy> depts) {
        dataProvider.setList(depts);
        sortHandler.setList(dataProvider.getList());
        dataProvider.refresh();
    }
}
